# encoding: utf-8
require 'digest/sha1'

class User
  include Mongoid::Document
  field :name, type: String
  field :username, type: String
  field :encrypted_password, type: String
  field :email
  field :salt
  field :gender, type: Integer

  has_many :articles

  validates :username, uniqueness: {case_sensitive: false, message: '已有该用户!'},
            length: {in: 4...32, message: '用户名在4-32个字符之内'}

  def safe_attributes
    self.as_json(only: [:username, :_id, :name, :email, :gender])
  end

  def update!(name, email, password, gender, old_password)
    raise '密码错误，拒绝修改！' unless User.auth(self.username, Digest::SHA1.hexdigest(old_password+self.salt))

    self.name, self.email, self.gender = name, email, gender
    change_password password if password
    self.save!
    self.safe_attributes
  end

  def change_password(password)
    raise '密码最低长度是6位' if password.length<6

    self.salt = Digest::SHA1.hexdigest(rand.to_s) unless self.salt
    self.encrypted_password = Digest::SHA1.hexdigest(password+self.salt)
  end

  def response_to_cookie(cookies)
    hashcode = Digest::SHA1.hexdigest(self.encrypted_password+$config['base']['secret_key'])
    cookies[$config['base']['auth_cookie_name']] = {
        value: "#{self.username}@#{hashcode}",
        expires: Time.now+7.days,
        path: '/'
    }
  end

  class << self
    def reg(username='', password='', gender=0)
      raise '私人博客，暂不开放注册' if User.all.count>0
      salt = Digest::SHA1.hexdigest(rand.to_s)
      encrypted_password = Digest::SHA1.hexdigest("#{password}#{salt}")
      user = User.new username: username, encrypted_password: encrypted_password,
                      gender: gender, salt: salt
      user.save!
      user
    end

    def login(username='', password='')
      user = User.where(username: username).first
      raise '没有该用户！' unless user

      encrypted_password = Digest::SHA1.hexdigest("#{password}#{user.salt}")
      authorized_user = User.auth(username, encrypted_password)
      raise '用户名或密码错误！' unless authorized_user
      authorized_user
    end

    def logout(cookies)
      cookies[$config['base']['auth_cookie_name']] = {
          expires: Time.now-7.days,
          path: '/'
      }
    end

    def auth_with_session(session={})

    end

    def auth_with_cookie(cookies={})
      cookie = cookies[$config['base']['auth_cookie_name']]
      return nil unless cookie
      username, hashcode = cookie.to_s.split('@')
      user = User.where(username: username).first
      return nil unless user
      result = hashcode == Digest::SHA1.hexdigest(user.encrypted_password+$config['base']['secret_key'])
      return user if result
      User.logout cookies
    end

    def auth(username, password)
      User.where(username: username, encrypted_password: password).first
    end
  end
end